# coding: utf-8
import base64
import os
import random
import string
import time
import logging

import requests
from PIL import Image
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from qiniu import Auth, put_file
from rest_framework import exceptions

from busness_manage.settings import QINIU_ACCESS_KEY, QINIU_SECRET_KEY, MEDIA_ROOT, QN_DOMAIN, QINIU_TOKEN

logger = logging.getLogger('django')


class QiniuServer():

    @property
    def qiniu_client(self):
        client = Auth(QINIU_ACCESS_KEY, QINIU_SECRET_KEY)
        return client

    def generate_token(self):
        bucket_name = 'busness-manage'
        token = self.qiniu_client.upload_token(bucket_name, expires=3600 * 24 * 365 * 1)
        return token

    def storage_to_qiniu(self, data):
        """上传base64图片到七牛"""
        Image_ROOT = os.path.join(MEDIA_ROOT, 'image')
        if isinstance(data, list):
            for d in data:
                s1 = base64.b64decode(d.split(',')[1])
                image_path = os.path.join(Image_ROOT, str(data.index(d)) + '.png')
                with open(f'{image_path}', 'wb')as f:
                    f.write(s1)
        else:
            s1 = base64.b64decode(str(data)[str(data).find(',') + 1:])
            endless = str(data)[:str(data).find(';')].split('/')[1]
            with open(f'{os.path.join(Image_ROOT,str(data.index(data)))}.{endless}', 'wb')as f:
                f.write(s1)
        file_list = os.listdir(Image_ROOT)
        url_list = []
        for file in file_list[:]:
            path = os.path.join(Image_ROOT, file)
            random_name = ''.join(
                random.sample(string.ascii_letters + string.digits, 7)) + f'{str(int(time.time()))}' + '.png'
            a = put_file(QINIU_TOKEN, random_name, path)
            if a[1].status_code == 200:
                url_list.append(QN_DOMAIN + random_name)
                os.remove(path)
            else:
                logger.info(a)
        return url_list

    def upload_qiniu(self, data):
        Image_ROOT = os.path.join(MEDIA_ROOT, 'image')
        path = default_storage.save(Image_ROOT + 'somename.jpg', ContentFile(data.read()))
        upload_path = Image_ROOT + '123.jpg'
        sImg = Image.open(path)
        w, h = sImg.size
        dImg = sImg.resize((int(w / 2), int(h / 2)), Image.ANTIALIAS)  # 设置压缩尺寸和选项，注意尺寸要用括号
        dImg.save(upload_path)
        random_name = ''.join(
            random.sample(string.ascii_letters + string.digits, 7)) + f'{str(int(time.time()))}' + '.jpg'
        a = put_file(QINIU_TOKEN, random_name, upload_path)
        if a[1].status_code == 200:
            os.remove(upload_path)
            return QN_DOMAIN + random_name
        else:
            logger.info(a)
            return

    def upload_base64(self, datas):
        if not isinstance(datas, list):
            raise exceptions.ValidationError('数据格式错误')
        url_list = []
        for data in datas:
            endless = str(data)[:str(data).find(';')].split('/')[1]
            data = str(data)[str(data).find(',') + 1:]
            random_name = ''.join(random.sample(string.ascii_letters + string.digits, 7))
            key = base64.b64encode((random_name + str(int(time.time())) + "." + endless).encode()).decode()
            url = f'http://upload-na0.qiniup.com/putb64/-1/key/{key}'
            ret = requests.Session().post(url, data, headers={'Authorization': 'UpToken ' + QINIU_TOKEN}, verify=False)
            res = ret.json().get('key')
            url_list.append(res)
        return url_list


qiniu_cli = QiniuServer()
# print(qiniu_cli.generate_token())
